//
//  Fraction.m
//  02-ClassAndObject
//
//  Created by dllo on 16/7/5.
//  Copyright © 2016年 yh. All rights reserved.
//

#import "Fraction.h"

@implementation Fraction

- (instancetype)initWithNumrator:(NSInteger)numrator denominator:(NSInteger)denominator {
    self = [super init];
    if (self) {
        _numrator = numrator;
        _denominator = denominator;
    }
    return self;
}

+ (instancetype)fractionWithNumrator:(NSInteger)numrator denominator:(NSInteger)denominator {
    return [[Fraction alloc] initWithNumrator:numrator denominator:denominator];
}

// 化简
- (NSInteger)redWithOneNum:(NSInteger)oneNum anotherNum:(NSInteger)anotherNum {
    while (oneNum % anotherNum) {
        NSInteger temp = oneNum;
        oneNum = anotherNum;
        anotherNum = temp % anotherNum;
    }
    return anotherNum;
}

// 化简
- (void)reduction {
    NSInteger sim = [self redWithOneNum:self.numrator anotherNum:self.denominator];
    self.numrator /= sim;
    self.denominator /= sim;
}

// 加法
- (Fraction *)addWith:(Fraction *)oneNum {
    NSInteger newNumrator = self.numrator * oneNum.denominator + self.denominator * oneNum.numrator;
    NSInteger newDenominator = self.denominator * oneNum.denominator;
    Fraction *result = [[Fraction alloc] initWithNumrator:newNumrator denominator:newDenominator];
    [result reduction];
    return result;
}

// 减法
- (Fraction *)subWith:(Fraction *)oneNum {
    NSInteger newNumrator = self.numrator * oneNum.denominator - self.denominator * oneNum.numrator;
    NSInteger newDenominator = self.denominator * oneNum.denominator;
    Fraction *result = [[Fraction alloc] initWithNumrator:newNumrator denominator:newDenominator];
    [result reduction];
    return result;
}

// 乘法
- (Fraction *)mulWith:(Fraction *)oneNum {
    NSInteger newNumrator = self.numrator * oneNum.numrator;
    NSInteger newDenominator = self.denominator * oneNum.denominator;
    Fraction *result = [[Fraction alloc] initWithNumrator:newNumrator denominator:newDenominator];
    [result reduction];
    return result;
}

// 除法
- (Fraction *)divWith:(Fraction *)oneNum {
    NSInteger newNumrator = self.numrator * oneNum.denominator;
    NSInteger newDenominator = self.denominator * oneNum.numrator;
    Fraction *result = [[Fraction alloc] initWithNumrator:newNumrator denominator:newDenominator];
    [result reduction];
    return result;
}

// 输出
- (void)info {
    NSLog(@"%ld / %ld", self.numrator, self.denominator);
}

@end
